package com.tanhua.dubbo.server.service;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huawei.ais.demo.ServiceAccessBuilder;
import com.huawei.ais.sdk.AisAccess;
import org.apache.http.HttpResponse;
import org.apache.http.entity.StringEntity;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

@Service
public class HuaweiYunService {

    public String moderation(String commend) {
        AisAccess service = ServiceAccessBuilder.builder()
                .ak("I3LAXPDA8XHDYDW3SP5L")
                .sk("caOsNJ5ZpVzuBmZmM7Md4PpFebTCfLYGrVJv34nF")
                .region("cn-east-3")
                .connectionTimeout(5000)
                .connectionRequestTimeout(1000)
                .socketTimeout(20000)
                .build();
        // 2.构建访问文本内容审核服务需要的参数
        String uri = "/v1.0/moderation/text";

        JSONObject json = new JSONObject();
        json.put("categories", new String[]{"porn", "politics", "flood"}); //检测内容
        JSONObject text = new JSONObject();
        text.put("text", commend);
        text.put("type", "content");
        JSONArray items = new JSONArray();
        items.add(text);
        json.put("items", items);
        StringEntity stringEntity = new StringEntity(json.toJSONString(), "utf-8");

// 3.传入文本内容审核服务对应的uri参数, 传入文本内容审核服务需要的参数，
// 该参数主要通过JSON对象的方式传入, 使用POST方法调用服务
        HttpResponse response = service.post(uri, stringEntity);
        String suggestion = null;
        try {
            InputStream content = response.getEntity().getContent();
            BufferedReader reader = IoUtil.getReader(content, "UTF-8");
            String readLine = reader.readLine();
            reader.close();
            cn.hutool.json.JSONObject jsonObject = new cn.hutool.json.JSONObject(readLine);
            cn.hutool.json.JSONObject result = (cn.hutool.json.JSONObject) jsonObject.get("result");
            suggestion = (String) result.get("suggestion");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return suggestion;

    }
}
